<?php

namespace App\Jobs\Stats\Retention\Day;

use App\Jobs\Stats\Stats as JobStats;
use App\Models\Admin\Stats\Retention\Day\Sign as Stats;
use App\Models\Game\Log\UserLogin;
use App\Models\Game\User\User;

class Sign extends JobStats
{

    /**
     * 留存统计天数
     *
     * @var int[]
     */
    protected $days = [1, 2, 3, 7, 15, 30];

    /**
     * 获取玩家ID列表
     *
     * @param int $timed
     * @param string $platCode
     * @return array|null
     */
    protected function getUserIds(int $timed, string $platCode): ?array
    {
        $data = User::dbTable()->selectRaw('min(id) as id_min,max(id) as id_max')
            ->where('registration_time', '>=', $timed)
            ->where('registration_time', '<', $timed + 86400)
            ->where('plat_code', $platCode)
            ->first();

        return is_null($data['id_min']) ? null : $data;
    }

    /**
     * 获取玩家人数
     *
     * @param int $timed
     * @param string $platCode
     * @param array $ids
     * @return int
     */
    protected function getUserCount(int $timed, string $platCode, array $ids): int
    {
        return UserLogin::dbTable()
            ->where('uid', '>=', $ids['id_min'])
            ->where('uid', '<=', $ids['id_max'])
            ->where('login_time', '>=', $timed)
            ->where('login_time', '<', $timed + 86400)
            ->where('plat_code', $platCode)
            ->distinct('uid')
            ->count();
    }

    /**
     * 执行统计任务。
     *
     * @return void
     */
    public function stats()
    {
        $timed = $this->task->timed;
        $platCode = $this->task->plat_code;

        foreach ($this->days as $day) {
            $timedDay = $timed - ($day - 1) * 86400;

            $ids = $this->getUserIds($timedDay, $platCode);

            $num = is_null($ids) ? 0 : $this->getUserCount($timed, $platCode, $ids);

            Stats::updateOrCreate([
                'timed' => $timedDay,
                'plat_code' => $platCode,
            ], [
                "drr_{$day}_num" => $num,
            ]);
        }
    }
}
